package com.nwpu.coursesupport.service.imple;

import com.nwpu.coursesupport.criteria.*;
import com.nwpu.coursesupport.entity.Class;
import com.nwpu.coursesupport.entity.*;
import com.nwpu.coursesupport.entity.bean.Files.FileItem;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.*;
import com.nwpu.coursesupport.exception.BatchTaskPersonalException;
import com.nwpu.coursesupport.mapper.*;
import com.nwpu.coursesupport.service.AbstractService;
import com.nwpu.coursesupport.service.TaskSubmitResultService;
import com.nwpu.coursesupport.service.param.IDListParam;
import com.nwpu.coursesupport.service.param.IDParam;
import com.nwpu.coursesupport.service.param.TaskSubmitResultServiceParam;
import com.nwpu.coursesupport.service.param.TaskSubmitResultServiceParam.CreatePersonalTaskParam;
import com.nwpu.coursesupport.tool.ServiceUtil;
import com.nwpu.coursesupport.tool.UpdateUtil;
import com.nwpu.coursesupport.view.StudentManagerView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class TaskSubmitResultServiceImple extends AbstractService implements TaskSubmitResultService{

	@Autowired
	private TaskSubmitResultMapper taskSubmitResultMapper;
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private AssistantMapper assistantMapper;
	@Autowired
	private ClassMapper classMapper;
	@Autowired
	private ClassStudentMapper classStudentMapper;
	@Autowired
	private TaskAssignmentMapper taskAssignmentMapper;
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private LessonMapper lessonMapper;
	@Autowired
	private AssistantCourseMapper assistantCourseMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private TeacherMapper teacherMapper;

    protected static Logger logger = LoggerFactory.getLogger(TaskSubmitResultServiceImple.class);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<TaskSubmitResult> findTaskSubmitResultById(Integer id) {
        return taskSubmitResultMapper.findTaskSubmitResultById(id);
    }

    public JSONResult detail(IDParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();
		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}
		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("该记录不存在");
			return rst.fail("该记录不存在");
		}

		// 对学生进行限制
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		int id = (int) getSession().getAttribute("id");
		if (roleType == RoleType.STUDENT) {
			if (taskSubmitResult.getAssignedId() != id && taskSubmitResult.getIsShare() == Status.NO) {
				logger.error("无权限");
				return rst.fail("无权限");
			}
		}
		Task task=null;
		if(taskSubmitResult.getType()==TaskType.TASKMAIN){//TaskMain
			TaskAssignment assign=this.taskAssignmentMapper.findById(taskSubmitResult.getAssignId());
			task=this.taskMapper.findById(assign.getTaskId());
		}else{//个人任务
			task=this.taskMapper.findById(taskSubmitResult.getAssignId());
		}
		rst.addData("taskSubmitResult", taskSubmitResult);
		rst.addData("courseId", task.getCourseId());
		rst.success();
		return rst;
	}

	public JSONResult taskMainList(TaskSubmitResultSearchCriteria sc) throws Exception{
		JSONResult rst = new JSONResult();
		rst.fail();
		if (sc == null || sc.getAssignId() == null) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		TaskAssignment assign=this.taskAssignmentMapper.findById(sc.getAssignId());
		if(assign==null){
			logger.error("该分配记录不存在");
			return rst.fail("该分配记录不存在");
		}
		Task task =this.taskMapper.findById(assign.getTaskId());
		if(task==null){
			logger.error("该项目不存在");
			return rst.fail("该项目不存在");
		}
		Lesson lesson = this.lessonMapper.findById(assign.getLessonId());
		sc.setType(TaskType.TASKMAIN);
		rst=list(sc);
		if(!rst.isSuccess()){
			return rst;
		}

		rst.addData("courseId", task.getCourseId());
		rst.addData("taskId",assign.getTaskId());
		rst.addData("task", task);
		rst.addData("lesson", lesson);
		rst.addData("assignId", sc.getAssignId());
		return rst;

	}

	public JSONResult taskPersonalList(TaskSubmitResultSearchCriteria sc) throws Exception{
		JSONResult rst = new JSONResult();
		rst.fail();
		if (sc == null || sc.getAssignId() == null) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		Task task=this.taskMapper.findById(sc.getAssignId());
		if(task==null){
			logger.error("该任务不存在");
			return rst.fail("该任务不存在");
		}
		sc.setType(TaskType.PERSONALTASK);
		rst=list(sc);
		if(!rst.isSuccess()){
			return rst;
		}
		rst.addData("courseId", task.getCourseId());
		rst.addData("taskId",sc.getAssignId());
		return rst;

	}

	private JSONResult list(TaskSubmitResultSearchCriteria sc) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		RoleType role = (RoleType) getSession().getAttribute("roleType");
		int id = (int) getSession().getAttribute("id");
		if (role == RoleType.ASSISTANT) {
			sc.setReviewId(id);
		} else {
			sc.setReviewId(null);
		}

		List<TaskSubmitResult> list = this.taskSubmitResultMapper.find(sc);
		if (list == null) {
			logger.error("数据查询失败");
			return rst.fail("数据查询失败");
		}

		rst.addData("list", list);
		rst.success();
		return rst;
	}

	public JSONResult searchUser(TaskSubmitResultServiceParam.SearchUserParam p) throws Exception{
		JSONResult rst = new JSONResult();
		rst.fail();
		if(p==null||p.getCourseId()<=0||p.getTaskId()<=0||p.getType()==null){
			logger.error("参数错误");
			return rst.fail("参数错误");
		}
		if(p.getType()==Useless_PersonTaskAssignType.STUDENT){
			StudentInCourseSearchCriteria scsc=new StudentInCourseSearchCriteria();
			scsc.setCourseId(p.getCourseId());
			scsc.setType(ClassType.CLASS);
			scsc.setKeywords(p.getKeywords());
			List<Student> list=this.classStudentMapper.getStudentByCourseId(scsc);

			TaskSubmitResultSearchCriteria sc=new TaskSubmitResultSearchCriteria();
			sc.setAssignId(p.getTaskId());
			sc.setRoleType(RoleType.STUDENT);
			sc.setType(TaskType.PERSONALTASK);
			List<Integer> ids=this.taskSubmitResultMapper.findByIds(sc);
			Iterator<Student> itor=list.iterator();
			while(itor.hasNext()){
				Student item=itor.next();
				if(ids.contains(item.getId())){
					itor.remove();
				}
			}
			rst.addData("list",list);
			rst.addData("type",p.getType());

		}else if(p.getType()==Useless_PersonTaskAssignType.ASSISTANT){
			AssistantCourseSearchCriteria acsc=new AssistantCourseSearchCriteria();
			acsc.setCourseId(p.getCourseId());
			acsc.setKeywords(p.getKeywords());
			List<Assistant> list=this.assistantCourseMapper.searchAssistantByCourseId(acsc);

			TaskSubmitResultSearchCriteria sc=new TaskSubmitResultSearchCriteria();
			sc.setAssignId(p.getTaskId());
			sc.setRoleType(RoleType.ASSISTANT);
			List<Integer> ids=this.taskSubmitResultMapper.findByIds(sc);
			Iterator<Assistant> itor=list.iterator();
			while(itor.hasNext()){
				Assistant item=itor.next();
				if(ids.contains(item.getId())){
					itor.remove();
				}
			}
			rst.addData("list",list);
			rst.addData("type",p.getType());
		}
		rst.success();
		return rst;
	}

	public JSONResult update(TaskSubmitResultServiceParam.UpdateParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if (UpdateUtil.setValues(taskSubmitResult, p) > 0) {
			if (!this.taskSubmitResultMapper.update(taskSubmitResult)) {
				logger.error("保存失败");
				return rst.fail("保存失败");
			}
		}

		rst.addData("taskSubmitResult", taskSubmitResult);
		rst.success();
		return rst;
	}

	public JSONResult personalTaskCreate(TaskSubmitResultServiceParam.CreatePersonalTaskParam p) throws BatchTaskPersonalException {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getAssignId() == null || p.getAssignId() == null) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		Task task = this.taskMapper.findById(p.getAssignId());
		if (task == null) {
			logger.error("该任务不存在");
			return rst.fail("该任务不存在");
		}

		Teacher t=this.courseMapper.getTeacherByCourseId(task.getCourseId());

		TaskSubmitResult ps = new TaskSubmitResult();
		ps.setType(TaskType.PERSONALTASK);
		//ps.setIsAnswerShow(Status.NO);
		Date assignDate =new Date();
		TaskSubmitResultSearchCriteria sc = new TaskSubmitResultSearchCriteria();
		if (p.getType() == Useless_PersonTaskAssignType.STUDENT) {// 学生
			Student st = this.studentMapper.findById(p.getAssignId());
			if (st == null) {
				logger.error("该学生不存在");
				return rst.fail("该学生不存在");
			}
			ps.setAssignId(p.getTaskId());
			ps.setAssignedId(st.getId());
			ps.setAssignedName(st.getName());
			ps.setRoleType(RoleType.STUDENT);
			List<TaskSubmitResult> list = this.taskSubmitResultMapper.find(sc);
			if (list.size() > 0) {
				logger.error("当前任务已分配给该学生");
				return rst.fail("当前任务已分配给该学生");
			}
			ps.setIsAnswerShow(Status.NO);
			ps.setStatus(SubmitTaskStatus.UNCOMMITTED);
			// 添加管理员
			StudentManagerSearchCriteria smsc = new StudentManagerSearchCriteria();
			smsc.setStudentId(st.getId());
			smsc.setClassType(ClassType.MANAGETEAM);
			StudentManagerView smView = this.classStudentMapper.getManagerView(smsc);
			if (smView == null) {
				ps.setReviewId(t.getId());
				ps.setReviewName(t.getName());
				ps.setReviewType(RoleType.TEACHER);
			}else{
				ps.setReviewId(smView.getManagerId());
				ps.setReviewName(smView.getManagerName());
				ps.setReviewType(RoleType.ASSISTANT);
			}
			ps.setAssignDate(assignDate);

			if (!this.taskSubmitResultMapper.save(ps)) {
				logger.error("该任务分配失败");
				return rst.fail("该任务分配失败");
			}
		} else if (p.getType() == Useless_PersonTaskAssignType.ASSISTANT) {// 助教
			Assistant st = this.assistantMapper.findById(p.getAssignId());
			if (st == null) {
				logger.error("该学生不存在");
				return rst.fail("该学生不存在");
			}
			ps.setAssignId(p.getTaskId());
			ps.setAssignedId(st.getId());
			ps.setAssignedName(st.getName());
			ps.setRoleType(RoleType.STUDENT);

			List<TaskSubmitResult> list = this.taskSubmitResultMapper.find(sc);
			if (list.size() > 0) {
				logger.error("当前任务已分配给该助教");
				return rst.fail("当前任务已分配给该助教");
			}
			ps.setIsAnswerShow(Status.NO);
			ps.setStatus(SubmitTaskStatus.UNCOMMITTED);

			int id = (int) getSession().getAttribute("id");// 获得老师id
			String name = (String) getSession().getAttribute("name");

			ps.setReviewId(id);
			ps.setReviewName(name);
			ps.setReviewType(RoleType.TEACHER);
			ps.setAssignDate(assignDate);
			if (!this.taskSubmitResultMapper.save(ps)) {
				logger.error("该任务分配失败");
				return rst.fail("该任务分配失败");
			}
		} else if (p.getType() == Useless_PersonTaskAssignType.CLASS) {// 班级
			Class c = this.classMapper.findById(p.getAssignId());
			if (c == null) {
				logger.error("该班级不存在");
				return rst.fail("该班级不存在");
			}
			ClassStudentSearchCriteria csc = new ClassStudentSearchCriteria();
			csc.setClassId(p.getAssignId());
			List<Student> sts = this.classStudentMapper.findStudentByParam(csc);
			if (sts.size() <= 0) {
				logger.error("该班级无相关学生");
				return rst.fail("该班级无相关学生");
			}

			List<TaskSubmitResult> pss = new ArrayList<TaskSubmitResult>();
			TaskSubmitResult item = null;
			for (Student s : sts) {
				sc = new TaskSubmitResultSearchCriteria();
				sc.setAssignId(p.getTaskId());
				sc.setRoleType(RoleType.STUDENT);
				sc.setAssignedId(s.getId());
				List<TaskSubmitResult> list = this.taskSubmitResultMapper.find(sc);
				if (list.size() > 0) {
					continue;
				}
				StudentManagerSearchCriteria smsc = new StudentManagerSearchCriteria();
				smsc.setStudentId(s.getId());
				smsc.setClassType(ClassType.MANAGETEAM);
				StudentManagerView smView = this.classStudentMapper.getManagerView(smsc);
				if (smView == null) {
					continue;
				}

				item = new TaskSubmitResult();
				item.setType(TaskType.PERSONALTASK);
				item.setAssignId(p.getTaskId());
				item.setAssignedId(s.getId());
				item.setAssignedName(s.getName());
				item.setRoleType(RoleType.STUDENT);
				item.setIsAnswerShow(Status.NO);
				item.setStatus(SubmitTaskStatus.UNCOMMITTED);
				item.setReviewId(smView.getManagerId());
				item.setReviewName(smView.getManagerName());
				item.setReviewType(RoleType.ASSISTANT);
				item.setAssignDate(assignDate);
				pss.add(item);
			}
			if (pss.size() <= 0) {
				logger.error("pss.size() <= 0");
				return rst.success();
			}
			if (this.taskSubmitResultMapper.batchSave(pss) != pss.size()) {
				logger.error("个人任务分配失败,抛出BatchTaskPersonalException");
				throw new BatchTaskPersonalException("个人任务分配失败");
			}

			if(task.getIsQuote()!=Status.YES){
				task.setIsQuote(Status.YES);
				if(!this.taskMapper.updateQuote(task)){
					logger.error("taskMain分配失败，抛出BatchTaskPersonalException");
					throw new BatchTaskPersonalException();
				}
			}

		} else {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		rst.success();
		return rst;
	}

	public JSONResult personalTaskBatchCreate(TaskSubmitResultServiceParam.BatchCreatePersonalTaskParam p)
			throws BatchTaskPersonalException {
		JSONResult rst = new JSONResult();
		rst.fail();
		if (p == null || p.getParams() == null || p.getParams().size() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		Task task = this.taskMapper.findById(p.getTaskId());
		if (task == null) {
			logger.error("该任务不存在");
			return rst.fail("该任务不存在");
		}
		Teacher t=this.courseMapper.getTeacherByCourseId(task.getCourseId());

		Set<TaskSubmitResult> result = new HashSet<TaskSubmitResult>();
		TaskSubmitResult ps = null;
		Date assignDate =new Date();
		for (CreatePersonalTaskParam param : p.getParams()) {
			if (param.getType() == Useless_PersonTaskAssignType.STUDENT) {
				Student st = this.studentMapper.findById(param.getAssignId());
				if (st == null) {
					continue;
				}
				ps = new TaskSubmitResult();
				ps.setType(TaskType.PERSONALTASK);
				ps.setAssignId(p.getTaskId());
				ps.setAssignedId(st.getId());
				ps.setAssignedName(st.getName());
				ps.setRoleType(RoleType.STUDENT);
				ps.setIsAnswerShow(Status.NO);
				ps.setStatus(SubmitTaskStatus.UNCOMMITTED);
				result.add(ps);
			} else if (param.getType() == Useless_PersonTaskAssignType.ASSISTANT) {
				Assistant st = this.assistantMapper.findById(param.getAssignId());
				if (st == null) {
					continue;
				}
				ps = new TaskSubmitResult();
				ps.setType(TaskType.PERSONALTASK);
				ps.setAssignId(p.getTaskId());
				ps.setAssignedId(st.getId());
				ps.setAssignedName(st.getName());
				ps.setRoleType(RoleType.ASSISTANT);
				ps.setIsAnswerShow(Status.NO);
				ps.setStatus(SubmitTaskStatus.UNCOMMITTED);
				result.add(ps);
			} else if (param.getType() == Useless_PersonTaskAssignType.CLASS) {
				Class c = this.classMapper.findById(param.getAssignId());
				if (c == null) {
					continue;
				}
				ClassStudentSearchCriteria csc = new ClassStudentSearchCriteria();
				csc.setClassId(param.getAssignId());
				List<Student> sts = this.classStudentMapper.findStudentByParam(csc);
				if (sts.size() <= 0) {
					continue;
				}
				for (Student s : sts) {
					ps = new TaskSubmitResult();
					ps.setType(TaskType.PERSONALTASK);
					ps.setAssignId(p.getTaskId());
					ps.setAssignedId(s.getId());
					ps.setAssignedName(s.getName());
					ps.setRoleType(RoleType.STUDENT);
					ps.setIsAnswerShow(Status.NO);
					ps.setStatus(SubmitTaskStatus.UNCOMMITTED);
					result.add(ps);
				}

			}
		}

		if (result.size() <= 0) {
			logger.error("result.size() <= 0");
			return rst.fail("您没有选择学生，或者所选小班中还未添加学生！");
		}
		TaskSubmitResultSearchCriteria sc = null;
		Iterator<TaskSubmitResult> itor = result.iterator();
		while (itor.hasNext()) {
			TaskSubmitResult item = itor.next();
			item.setAssignDate(assignDate);
			sc = new TaskSubmitResultSearchCriteria();
			sc.setAssignId(item.getAssignId());
			sc.setRoleType(item.getRoleType());
			sc.setAssignedId(item.getAssignedId());
			List<TaskSubmitResult> seach = this.taskSubmitResultMapper.find(sc);// 是否已经分配该任务
			if (seach.size() > 0) {
				itor.remove();
				continue;
			}
			if (item.getRoleType() == RoleType.ASSISTANT) {
				/*int id = (int) getSession().getAttribute("id");// 获得老师id
				String name = (String) getSession().getAttribute("name");*/
				item.setReviewId(t.getId());
				item.setReviewName(t.getName());
				item.setReviewType(RoleType.TEACHER);
			} else if (item.getRoleType() == RoleType.STUDENT) {
				StudentManagerSearchCriteria smsc = new StudentManagerSearchCriteria();
				smsc.setStudentId(item.getAssignedId());
				smsc.setClassType(ClassType.MANAGETEAM);
				smsc.setCourseId(task.getCourseId());
				StudentManagerView smView = this.classStudentMapper.getManagerView(smsc);
				if (smView == null) {//该学生未加入到相关的管理班级中
					item.setReviewId(t.getId());
					item.setReviewName(t.getName());
					item.setReviewType(RoleType.TEACHER);
				}else{
					item.setReviewId(smView.getManagerId());
					item.setReviewName(smView.getManagerName());
					item.setReviewType(RoleType.ASSISTANT);
				}

			} else {
				continue;
			}

		}
		List<TaskSubmitResult> submit = new ArrayList<TaskSubmitResult>(result);
		if(submit.size()<=0){
			return rst.success();
		}
		if (this.taskSubmitResultMapper.batchSave(submit) != submit.size()) {
			logger.error("批量发布个人任务失败，并抛出异常BatchTaskPersonalException");
			throw new BatchTaskPersonalException("个人任务分配失败");
		}
		if(task.getIsQuote()!=Status.YES){
			task.setIsQuote(Status.YES);
			if(!this.taskMapper.updateQuote(task)){
				logger.error("taskPersonal分配失败，并抛出异常BatchTaskPersonalException");
				throw new BatchTaskPersonalException();
			}
		}

		rst.success();
		return rst;
	}

	public JSONResult batchReview(TaskSubmitResultServiceParam.BatchReviewParam p) throws Exception{
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getBatchReview().size() <= 0 || p.getCourseId() <= 0) {
			logger.error("batchReview参数有误，数据为空");
			return rst.fail("参数有误，数据为空，请重新尝试！");
		}
		Course course = this.courseMapper.findById(p.getCourseId());
		if(course == null) {
			logger.error("batchReview参数有误，课程号无效");
			return rst.fail("参数有误，请重新尝试！");
		}

		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		int id = (int) getSession().getAttribute("id");

		if (roleType == RoleType.TEACHER) {
			if (id != course.getTid()) {
				logger.error("#####id为"+id+"的教师在"+df.format(new Date())+" batchReview批量评分课程名为"+course.getName()+"失败");
				return rst.role("对不起，权限不够！");
			}
		}else if(roleType == RoleType.ASSISTANT) {
			List<Assistant> assistantIdList = this.assistantCourseMapper.getAssistantByCourseId(id);
			if (assistantIdList == null || assistantIdList.size() <= 0) {
				logger.error("#####id为"+id+"的助教在"+df.format(new Date())+" batchReview批量评分课程名为"+course.getName()+"失败");
				return rst.role("对不起，权限不够！");
			}else {
				int flag = 0;
				Iterator<Assistant> iterator = assistantIdList.iterator();
				while(iterator.hasNext()){
					if(iterator.next().getId()==id){
						flag = 1;
					}
				}
				if (flag == 0) {
					logger.error("#####id为"+id+"的助教在"+df.format(new Date())+" batchReview批量评分课程名为"+course.getName()+"失败");
					return rst.role("对不起，权限不够！");
				}
			}

		}else {
			logger.error("角色为"+roleType+"，id为"+id+"的用户在"+df.format(new Date())+" 尝试批量评分失败");
			return rst.role("对不起，权限不够！");
		}


		List<TaskSubmitResultServiceParam.ReviewParam> listReview = p.getBatchReview();
		Iterator<TaskSubmitResultServiceParam.ReviewParam> iterator = listReview.iterator();
		//判断当前任务的提交情况和评分情况。若没有提交，修改提交状态并给分；若已评分，则修改
		List<TaskSubmitResult> taskSubmitResultList = new ArrayList<TaskSubmitResult>();
		TaskSubmitResultServiceParam.ReviewParam reviewParam;
		TaskSubmitResult taskSubmitResult = null;
		while(iterator.hasNext()){
			reviewParam = iterator.next();
			taskSubmitResult = this.taskSubmitResultMapper.findById(reviewParam.getId());
			if (taskSubmitResult!=null) {
				taskSubmitResult.setScore(reviewParam.getScore());
				taskSubmitResult.setEvaluate(reviewParam.getEvaluate());
				taskSubmitResult.setReviewId(id);
				taskSubmitResult.setReviewType(roleType);

				if (taskSubmitResult.getStatus() == SubmitTaskStatus.UNCOMMITTED) {
					taskSubmitResult.setUploadTime(new Date());
					taskSubmitResult.setDetail("");
					taskSubmitResult.setResultAttachmentBytes("{\"files\":[]}");
				}

				taskSubmitResultList.add(taskSubmitResult);
			}
		}
		if (taskSubmitResultList.size() <= 0) {
			logger.error("提交的数据有误，batchReview");
			return rst.fail("参数有误，请重新尝试！");
		}
		for (TaskSubmitResult tsr : taskSubmitResultList) {
			tsr.setMarkDate(new Date());
			tsr.setStatus(SubmitTaskStatus.HAVEREAD);

			if(!this.taskSubmitResultMapper.batchReviewTask(tsr)){
				logger.error("#####id为"+id+"的"+roleType.toString()+"在"+df.format(new Date())+" batchReview课程名为"+course.getName()+"批量评分taskSubmitResult_id为"+tsr.getId()+"失败");
				throw new Exception("评分失败！请重新尝试！");
			}
		}

		rst.success();
		return rst;
	}

	public JSONResult review(TaskSubmitResultServiceParam.ReviewParam p) {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if (taskSubmitResult.getStatus() == SubmitTaskStatus.UNCOMMITTED) {
			logger.error("还未提交，无法操作");
			return rst.role("还未提交，无法操作");
		}

		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		int id = (int) getSession().getAttribute("id");
		if (roleType == RoleType.ASSISTANT) {
			if (taskSubmitResult.getReviewId() != id) {
				logger.error("你没有该权限");
				return rst.role("你没有该权限");
			}
		}

		taskSubmitResult.setReviewId(id);
		taskSubmitResult.setReviewType(roleType);
		taskSubmitResult.setScore(p.getScore());
		taskSubmitResult.setEvaluate(p.getEvaluate());
		taskSubmitResult.setMarkDate(new Date());
		taskSubmitResult.setStatus(SubmitTaskStatus.HAVEREAD);

		if (!this.taskSubmitResultMapper.reviewTask(taskSubmitResult)) {
			logger.error("批改失败");
			return rst.fail("批改失败");
		}

		rst.success();
		return rst;
	}

	public JSONResult reUploadFile(TaskSubmitResultServiceParam.SubmitParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();
		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());

		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}
		int id = (int) getSession().getAttribute("id");
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		Teacher teacher = this.teacherMapper.findById(id);
		//TODO:只检验这部分是不行的，还需要验证该任务是否是该教师或者该教师的助教创建的——检验该任务所属的课程是否是该教师所授
		if(roleType != RoleType.TEACHER || teacher == null){
			logger.error("你没有操作权限");
			return rst.fail("你没有操作权限");
		}

		TaskAssignment assign = this.taskAssignmentMapper.findById(taskSubmitResult.getAssignId());
		if (assign == null) {
			logger.error("无该任务发布记录");
			return rst.fail("无该任务发布记录");
		}
		Date date = new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		taskSubmitResult.setDetail(taskSubmitResult.getDetail()+"<br>(于"+sdf.format(date)+"由("+teacher.getName()+")老师 补交附件)");
		taskSubmitResult.setResultAttachmentBytes(ServiceUtil.serializeFiles(p.getResultAttachment()));
		taskSubmitResult.setUploadTime(new Date());
		taskSubmitResult.setStatus(taskSubmitResult.getStatus());
		if (!this.taskSubmitResultMapper.submitTask(taskSubmitResult)) {
			logger.error("保存失败");
			return rst.fail("保存失败");
		}
		rst.success();

		return rst;
	}
	public JSONResult submit(TaskSubmitResultServiceParam.SubmitParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			return rst.fail("参数有误");
		}

		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());

		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}
		int id = (int) getSession().getAttribute("id");
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		if (!(id == taskSubmitResult.getAssignedId()&&roleType==taskSubmitResult.getRoleType())) {
			logger.error("无操作权限");
			return rst.role("无操作权限");
		}
		if (taskSubmitResult.getStatus() == SubmitTaskStatus.HAVEREAD) {
			logger.error("该任务已批改，无权限修改");
			return rst.fail("该任务已批改，无权限修改");
		}
		if (taskSubmitResult.getType() != TaskType.PERSONALTASK) {// 表示为TaskMain类任务
			TaskAssignment assign = this.taskAssignmentMapper.findById(taskSubmitResult.getAssignId());
			if (assign == null) {
				logger.error("无该任务发布记录");
				return rst.fail("无该任务发布记录");
			}
			Date date = new Date();
			if (assign.getDeadline().before(date)) {
				logger.error("已超过该任务提交的截止时间，无法提交");
				return rst.fail("已超过该任务提交的截止时间，无法提交");
			}
		}

		taskSubmitResult.setDetail(p.getDetail());
		taskSubmitResult.setResultAttachmentBytes(ServiceUtil.serializeFiles(p.getResultAttachment()));
		taskSubmitResult.setUploadTime(new Date());
		taskSubmitResult.setStatus(SubmitTaskStatus.COMMITTED);
		if (!this.taskSubmitResultMapper.submitTask(taskSubmitResult)) {
			logger.error("保存失败");
			return rst.fail("保存失败");
		}

		rst.success();

        TaskAssignment assign = this.taskAssignmentMapper.findById(taskSubmitResult.getAssignId());
        Student student = studentMapper.findById(id);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("同学:").append(student.getName()).append(",").append("你成功提交了：");

//        Task task = taskMapper.findById(assign.getTaskId());
//        stringBuilder.append(task.getTitle() + "的作业。");

		try{
			Task task = taskMapper.findById(assign.getTaskId());
			stringBuilder.append(task.getTitle() + "的作业。");
		}catch(Exception e){
			stringBuilder.append("个人任务的作业。");
		}

        if (!CollectionUtils.isEmpty(p.getResultAttachment().getFiles())) {
            FileItem file = p.getResultAttachment().getFiles().get(0);
            String url = file.getUrl();
            Resource resource = resourceService.detail(url);
            long length = new File(resource.getUrl()).length();
            length = length / 1024;
            String fileName = resource.getFileName();
            stringBuilder.append("附件：").append("文件：").append(fileName).append(", 文件大小:").append(length).append("K");

        } else {
            stringBuilder.append("无附件");
        }
        System.out.println("f::" + stringBuilder.toString());
        rst.success();

        try {
			qqEmailService.sendQQMail(student.getEmail(), "作业提交成功",stringBuilder.toString(), null);
		} catch (Exception e){
			rst.fail("提交成功！您还未添加邮箱，添加后即可获取作业提交情况！");
		}

        return rst;
	}
    @Autowired
    private QQEmailService qqEmailService;

    @Autowired
    private ResourceService resourceService;
	public JSONResult remove(IDParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getId() <= 0) {
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}

		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if (!this.taskSubmitResultMapper.delete(p.getId())) {
			logger.error("删除失败");
			return rst.fail("删除失败");
		}
		rst.addData("taskSubmitResult", taskSubmitResult);
		rst.success();
		return rst;
	}

	public JSONResult shareSubmit(TaskSubmitResultServiceParam.ShareSubmitParam p){
		JSONResult rst = new JSONResult();
		rst.fail();
		if(p==null||p.getId()<=0){
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if(taskSubmitResult.getType()!=TaskType.TASKMAIN){
			logger.error("该操作无效-个人任务无法共享");
			return rst.fail("个人任务无法共享");
		}

		if(UpdateUtil.setValues(taskSubmitResult,p)>0){
			taskSubmitResult.setShareDate(new Date());
			if(!this.taskSubmitResultMapper.shareTask(taskSubmitResult)){
				logger.error("共享失败");
				return rst.fail("共享失败");
			}
		}

		rst.success();
		return rst;
	}

	public JSONResult updateAnswerStatus(TaskSubmitResultServiceParam.DealAnswerVisible p){
		JSONResult rst = new JSONResult();
		rst.fail();
		if(p==null||p.getId()<=0){
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		TaskSubmitResult taskSubmitResult = this.taskSubmitResultMapper.findById(p.getId());
		if (taskSubmitResult == null) {
			logger.error("记录不存在或已被删除");
			return rst.fail("记录不存在或已被删除");
		}

		if(taskSubmitResult.getType()!=TaskType.PERSONALTASK){
			logger.error("该操作无效");
			return rst.fail("该操作无效");
		}

		taskSubmitResult.setIsAnswerShow(p.getIsAnswerVisible());
		if (!this.taskSubmitResultMapper.updateAnswerStatus(taskSubmitResult)) {
			logger.error("删除失败");
			return rst.fail("删除失败");
		}

		rst.success();
		return rst;
	}

	public JSONResult batchUpdateAnswerStatus(BatchDealAnswerSearchCriteria p){
		JSONResult rst = new JSONResult();
		rst.fail();
		if(p==null||p.getList().size()<=0||p.getIsAnswerVisible()==null){
			logger.error("参数有误");
			return rst.fail("参数有误");
		}
		p.setType(TaskType.PERSONALTASK);

		if (!this.taskSubmitResultMapper.batchUpdateAnswerVisible(p)) {
			logger.error("删除失败");
			return rst.fail("删除失败");
		}

		rst.success();
		return rst;
	}

	public JSONResult removeAll(IDListParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();

		if (p == null || p.getIds() == null || p.getIds().isEmpty()) {
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}

		this.taskSubmitResultMapper.batchDelete(p.getIds());

		rst.success();
		return rst;
	}

	public JSONResult changeStatus(IDParam p) throws Exception {
		JSONResult rst = new JSONResult();
		rst.fail();
		if(p == null || p.getId() == null || p.getId() <= 0){
			logger.error("参数有误");
			rst.fail("参数有误");
			return rst;
		}

		int id = (int) getSession().getAttribute("id");
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		Teacher teacher = this.teacherMapper.findById(id);
		if(roleType != RoleType.TEACHER || teacher == null){
			logger.error("你没有操作权限");
			return rst.fail("你没有操作权限");
		}

		TaskSubmitResultSearchCriteria tsrSC = new TaskSubmitResultSearchCriteria();
		tsrSC.setAssignId(p.getId());
		List<TaskSubmitResult> taskSubmitResult = this.taskSubmitResultMapper.find(tsrSC);
		if(taskSubmitResult.size() <= 0){
			logger.error("分配信息有误");
			return rst.fail("分配信息有误");
		}
		//移除已提交/已批改的
		Iterator<TaskSubmitResult> itor=taskSubmitResult.iterator();
		while(itor.hasNext()){
			TaskSubmitResult t=itor.next();
			if(t.getStatus()!=SubmitTaskStatus.UNCOMMITTED){
				itor.remove();
			}
		}
		if(taskSubmitResult.size() <= 0){
			logger.error("所有学生都已提交");
			return rst.fail("所有学生都已提交");
		}
		//更改状态
		for(TaskSubmitResult tsr : taskSubmitResult){
			tsr.setStatus(SubmitTaskStatus.COMMITTED);
			Date date = new Date();
			tsr.setUploadTime(date);
			tsr.setDetail("");
			tsr.setResultAttachmentBytes("{\"files\":[]}");
			if(!this.taskSubmitResultMapper.submitTask(tsr)){
				logger.error("更新任务提交状态失败，并抛出异常Exception");
				throw new Exception("更新任务提交状态失败");
			}
		}

		rst.success();
		return rst;
	}

	@Override
	public Double findSumScoreByAssignID(List<Integer> assignmentID) {
//		System.out.println(taskSubmitResultMapper.findSumScoreByAssignID(assignmentID).toString());
		return taskSubmitResultMapper.findSumScoreByAssignID(assignmentID);
	}

	@Override
	public Double findAnsNumByAssignID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findAnsNumByAssignID(assignmentID);
	}

	@Override
	public Double findMidScoreByAssignID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findMidScoreByAssignID(assignmentID);
	}

	@Override
	public Double findStdScoreByAssignID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findStdScoreByAssignID(assignmentID);
	}

	@Override
	public Double findTopScoreByAssignID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findTopScoreByAssignID(assignmentID);
	}

	@Override
	public Double findLowScoreByAssignID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findLowScoreByAssignID(assignmentID);
	}

	@Override
	public List<String> findAllStuName(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findAllStuName(assignmentID);
	}

	@Override
	public List<Integer> findAllStuID(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findAllStuID(assignmentID);
	}

	@Override
	public List<Double> findAllStuScore(List<Integer> assignmentID) {
		return taskSubmitResultMapper.findAllStuScore(assignmentID);
	}

	@Override
	public List<FileItem> getAllFileUrl(IDParam p) {

		if(p == null || p.getId() == null || p.getId() <= 0){
			logger.error("参数有误-批量下载文件");
			return null;
		}

		int id = (int) getSession().getAttribute("id");
		RoleType roleType = (RoleType) getSession().getAttribute("roleType");
		Teacher teacher = this.teacherMapper.findById(id);

		//TODO:需进一步加强权限安全
		if(roleType != RoleType.TEACHER || teacher == null){
			logger.error("你没有操作权限-批量下载文件");
			return null;
		}
		TaskSubmitResultSearchCriteria tsrSC = new TaskSubmitResultSearchCriteria();
		tsrSC.setAssignId(p.getId());
		List<TaskSubmitResult> taskSubmitResult = this.taskSubmitResultMapper.find(tsrSC);
		if(taskSubmitResult.size() <= 0){
			logger.error("分配信息有误--批量下载文件");
			return null;
		}
		List<FileItem> filist = new ArrayList<>();
		String url = "";
		for(TaskSubmitResult tsResult : taskSubmitResult){
			List<FileItem> resultFileItem = ServiceUtil.DeserializeFiles(tsResult.getResultAttachmentBytes()).getFiles();
			Student student = this.studentMapper.findById(tsResult.getAssignedId());
			int i=1;
			for(FileItem fileItem : resultFileItem){
				url = fileItem.getUrl();
				//JOBDONE:对每个学生提交的文件添加学号
				if(!url.equals("")&&!url.equals(" ")&&url!=null){
					//TODO:待修改 文件名越靠前需要越靠后添加 当前文件命名为 序号-[学号]_[姓名]_成绩{score-double}_文件原名（文件原名中包含学号和成绩则不再额外添加）
					//添加成绩
					fileItem.setName("score-"+tsResult.getScore()+"_"+fileItem.getName());
					//没有学生姓名，添加
					if(fileItem.getName().indexOf(tsResult.getAssignedName()) == -1){
						fileItem.setName(tsResult.getAssignedName()+"_"+fileItem.getName());
					}
					//没有学生学号，添加
					if(fileItem.getName().indexOf(student.getStudentCode()) == -1){
						fileItem.setName(student.getStudentCode()+"_"+fileItem.getName());
					}
					//添加编号
					fileItem.setName(i+"-"+fileItem.getName());
					++i;

					filist.add(fileItem);
				}
			}
		}
		return filist;
	}

	@Override
	public String getInfoZip(int assignId) {
		//JOBDONE:更精准命名+任务名
		TaskAssignment ta = this.taskAssignmentMapper.findById(assignId);
		if(ta == null){
			logger.error("批量下载-getInfoZip-无效的分配id");
			return null;
		}
		Task t = this.taskMapper.findById(ta.getTaskId());
		if(t == null){
			logger.error("批量下载-getInfoZip-无效的任务id");
			return null;
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		return t.getTitle()+"_班级_"+ta.getClassName()+"_分配时间_"+formatter.format(ta.getAssignDate())+".zip";
	}

	//TODO:解析detail中的图片  to delete
	/*public List<String> getDetailFile(String detail){
		List<String> ls = new ArrayList<>();
		int start = 0, end = 0;
		String s = null;
		while(detail.contains("<img")){
			start = detail.indexOf("picture/");
			end = detail.indexOf(" alt=");
			s=detail.substring(start+1, end);
			if(s != null){
				ls.add(s);
			}

		}
		return ls;
	}*/
}
